<?php
class VoteService {
	const SUCCESS = 'success';
	const ERROR = 'error';
	//初始票数
	private $_tickets = 1;
	//每日投票次数
	private $_max = 10;
	//初始化时间
	private $_startTime;
	
	private $_error = array (1 => "投票已结束，欢迎你的参与", 2 => "违规投票，等待审查" );
	
	/**
	 * 每日投票数
	 */
	public function __construct() {
		$this->_startTime = strtotime ( date ( "Ymd", time () ) );
	}
	
	/**
	 * 投票
	 * @param int $id 投票对象
	 * @param int $uid  投票人id
	 */
	public function addTickets($id, $uid) {
		if (! $uid) {
			return "请先登录";
		}
		
		if ($id < 1) {
			return "投票失败，请选择投票对象";
		}
		
		//检查投票是否到期
		//检查是否已经投过票
		if ($this->checkVoteTickets ( $uid )) {
			return "今天的投票数已用完";
		}
		
		//检查是否已经参赛 没有就新增 有的更新
		if (! $this->checkUserExist ( $id )) {
			
			if ($status = $this->isExpired ( $id )) {
				return $this->_error [$status];
			}
			
			VoteModel::instance ()->saveTicketsById ( $id );
		} else {
			VoteModel::instance ()->addUser ( array ('id' => $id, 'tickets' => $this->_tickets ) );
		}
		//增加历史记录
		$this->addVoteLog ( $uid, $id );
		return self::SUCCESS;
	}
	
	/**
	 * 
	 * 投票是否过期
	 * @param int $id
	 * @return true or false
	 */
	public function isExpired($id) {
		$rs = VoteModel::instance ()->getTicketsById ( $id );
		return $rs ['status'];
	
	}
	/**
	 * 返回所有票数
	 * @return id tickets
	 */
	public function getAllTickets() {
		return VoteModel::instance ()->getAllTickets ();
	}
	/**
	 * 检查投票次数
	 * @return true 超过了 false 没有
	 */
	private function checkVoteTickets($uid) {
		$num = VoteModel::instance ()->countTicketsByTime ( $uid, $this->_startTime );
		return $num ['num'] >= $this->_max ? true : false;
	}
	
	/**
	 * 
	 * @param int $uid 投票人id
	 * @param int $gid 对象id
	 */
	private function addVoteLog($uid, $gid) {
		VoteModel::instance ()->addList ( array ('uid' => $uid, 'userid' => $gid, 'add_time' => time () ) );
	}
	
	/**
	 * 检查用户是否存在
	 * @param int $id
	 * @return ture 不存在 false 存在
	 */
	private function checkUserExist($id) {
		$rs = VoteModel::instance ()->getTicketsById ( $id );
		return empty ( $rs );
	
	}

}